package com.gdb.controller;

import java.util.Collection;

import org.hibernate.HibernateException;
import org.hibernate.classic.Session;

import com.gdb.model.Guitar;
import com.gdb.util.HibernateUtil;

public class GuitarControl extends HibernateUtil {

	public Guitar add(Guitar g) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(g);
		session.getTransaction().commit();
		return g;
	}

	public Guitar delete(Long id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Guitar guitar = (Guitar) session.load(Guitar.class, id);
		if (null != guitar) {
			session.delete(guitar);
		}
		session.getTransaction().commit();
		return guitar;
	}

	@SuppressWarnings("unchecked")
	public Collection<Guitar> list() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Collection<Guitar> guitars = null;

		try {
			guitars = (Collection<Guitar>) session.createQuery("from Guitar")
					.list();
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}

		session.getTransaction().commit();

		return guitars;
	}

}
